package com.zjitc.controller;

import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.Car;
import com.zjitc.pojo.Caritem;
import com.zjitc.pojo.User;
import com.zjitc.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/20  16:59
 */
@Controller
@RequestMapping("/car")
public class CarController {
    @Autowired
    private CarService service;

    private static final String USER = "user";

    @RequestMapping("/add2cart")
    public ModelAndView cart (HttpSession session, HttpServletRequest request,String pid,Integer count) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Object o = session.getAttribute(USER);
        ModelAndView mv = new ModelAndView();
        if(o == null){
            String msg = "客官请先登录，再操作购物车...";
            String address = request.getContextPath() + "login";
            mv.addObject("msg",msg);
            mv.addObject("address",address);
            mv.setViewName("msg");
        }else{
            User user = (User) o ;
            service.add2car(user.getUid(),count,pid);
            mv.setViewName("redirect:/car/showcar.do");
        }
        return mv;
    }

    @RequestMapping("/showcar")
    public ModelAndView show(HttpSession session) throws ServletException, IOException {
        User user = (User) session.getAttribute(USER);
        List<Caritem> items = service.findAll(user.getUid());
        double total = 0.0;
        for(Caritem caritem : items){
            total+=caritem.getPrice();
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("items",items);
        mv.addObject("total",total);
        mv.setViewName("cart");
        return mv;
    }

    @RequestMapping("/deletecar")
    public ModelAndView delete(String uid) throws ServletException, IOException {
        ModelAndView modelAndView = new ModelAndView();
        int success = service.deleteAll(uid);
        modelAndView.setViewName("redirect:/car/showcar.do");
        return modelAndView;
    }

    @RequestMapping("/deletesingle")
    @ResponseBody
    public ServerResponse<Car> deletesingle(@RequestParam("uid")String uid, @RequestParam("pid") String pid) throws ServletException, IOException {
        return service.deletesingle(pid,uid);
    }
}
